/*jslint browser: true, devel: true*/
/*global $ window*/
/**
 *  通用API请求接口
 **/
const CommonApi = {

    ajaxRequestTimeout : 10000,

    // 通用查询ajax请求
    httpGetRequest : function (requestUrl, successHandler, errorHandler) {
        console.log('request url: ' + requestUrl);
        const ajaxGetRequest = $.ajax({
            url: requestUrl,
            type: 'get',
            dataType: 'json',
            async: true,
            timeout: CommonApi.ajaxRequestTimeout,
            beforeSend: function (request) {
                request.setRequestHeader('Content-Type', 'application/json');
            },
            // xhrFields:{
            //     withCredentials: true
            // },
            success: function (dbResponse) {
                successHandler(dbResponse);
            },
            error: function (XMLHttpRequest, status, errorThrown) {
                if ('timeout' != status) {
                    console.log(new Date + '[log info,请求异常 : ' + status + ':' + errorThrown + ']');
                    globalUiKit.notify('', '请求数据失败', 'error');
                }
                if(errorHandler) {
                    errorHandler();
                }
            },
            complete: function (XMLHttpRequest, status) {
                if ('timeout' === status) {
                    globalUiKit.notify('', i18n.promptMessage.lobibox.requestTimeOut, 'error');
                    ajaxGetRequest.abort();
                }
            }
        });
    },

    /**
     * 通用查询post请求
     *
     * @param url
     * @param data
     * @param successHandler
     * @param errorHandler
     */
    httpPostRequest: function (url, data, successHandler, errorHandler) {
        console.log('request url: ' + url + ', data: ' + data);
        if (!data || !url) {
            return;
        }

        const ajaxPostRequest = $.ajax({
            data: JSON.stringify(data),
            url: url,
            type: 'post',
            dataType: 'json',
            timeout: CommonApi.ajaxRequestTimeout,
            beforeSend: function (request) {
                request.setRequestHeader('Content-Type', 'application/json');
            },
            success: function (data) {
                successHandler(data);
            },
            error: function (XMLHttpRequest, status, errorThrown) {
                if ('timeout' != status) {
                    console.log(new Date + '[log info,请求异常 : ' + status + ':' + errorThrown + ']');
                    globalUiKit.notify('', '请求数据失败', 'error');
                }
                if(errorHandler) {
                    errorHandler();
                }
            },
            complete: function (XMLHttpRequest, status) {
                if ('timeout' === status) {
                    globalUiKit.notify('', i18n.promptMessage.lobibox.requestTimeOut, 'error');
                    ajaxPostRequest.abort();
                }
            }
        });
    },
};